package com.itheima.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.entity.Result;
import com.itheima.service.MemberService;
import com.itheima.service.ReportService;
import com.itheima.service.SetmealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/*
会员数量统计
 */
@RestController
@RequestMapping("/report")
public class ReportController {

    @Reference
    private MemberService memberService;

    @Reference
    private SetmealService setmealService;

    @Reference
    private ReportService reportService;

    //查询一年内每月会员数量
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        /*
        需要的数据类型，所以返回的数据用map,map中是两个list集合
        months: ['2020.01', '2020.02, '2020.03']
        memberCount: [100,200,300]
        */
        //创建日期类，默认是当前日期
        Calendar c = Calendar.getInstance();

        //把当前日期往前推12月
        c.add(Calendar.MONTH,-12);

        List<String> months = new ArrayList<>();
        for (int i = 0; i <12 ; i++) {//循环12次把日期装入集合中
            c.add(Calendar.MONTH,1);
            Date date = c.getTime();//获取当前日期

            //因为需要的是string类型数据所以进行类型转换
            String moth = new SimpleDateFormat("yyyy.MM").format(date);

            //将得到的字符串存入集合中
            months.add(moth);
        }

        //根据月份集合查询数据库，获得会员数量集合
        List<Integer> memberCount = null;
        try {
            memberCount = memberService.findMemberCountByMonths(months);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_FAIL);
        }

        Map<String, Object> map = new HashMap<>();
        map.put("months",months);
        map.put("memberCount",memberCount);

        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }

    //会员预约的各个套餐占比情况
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        /*
        前端需要的数据类型
        setmealNames: ['套餐1', '套餐2', '套餐3', '套餐4', '套餐5']
        setmealCount: [
                {value: 335, name: '套餐1'},
                {value: 310, name: '套餐2'},
                {value: 234, name: '套餐3'},
                {value: 135, name: '套餐4'},
                {value: 1548, name: '套餐5'}
            ]
         */
        //查询会员预约的各个套餐的数量，因为前端setmealCount需要的格式，所以封装用List<Map<String,Object>>类型
        try {
            List<Map<String,Object>> setmealCount = setmealCount = setmealService.findSetmealCount();

            //创建集合封装setmealNames
            List<String> setmealNames = new ArrayList<>();

            //setmealCount中有setmealNames需要的数据，所以不用重复查询，直接从setmealCount中取
            if(setmealCount != null && setmealCount.size() > 0) {
                for (Map<String, Object> map1 : setmealCount) {
                    String name = (String) map1.get("name");
                    setmealNames.add(name);
                }
            }

            //将前端需要的数据封装到map中
            Map<String, Object> map = new HashMap<>();
            map.put("setmealNames",setmealNames);
            map.put("setmealCount",setmealCount);

            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }

    //运营数据统计
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        /*
        reportData:{
                    reportDate:null,  日期
                    todayNewMember :0, 新增会员数
                    totalMember :0, 总会员数
                    thisWeekNewMember :0, 本周新增会员数
                    thisMonthNewMember :0, 本月新增会员数
                    todayOrderNumber :0,  今日预约数
                    todayVisitsNumber :0,  今日到诊数
                    thisWeekOrderNumber :0, 本周预约数
                    thisWeekVisitsNumber :0, 本周到诊数
                    thisMonthOrderNumber :0, 本月预约数
                    thisMonthVisitsNumber :0, 本月到诊数
                    hotSetmeal :[ 热门套餐： name套餐名称  setmeal_count预约数量  proportion占比
                        {name:'阳光爸妈升级肿瘤12项筛查（男女单人）体检套餐',setmeal_count:200,proportion:0.222},
                        {name:'阳光爸妈升级肿瘤12项筛查体检套餐',setmeal_count:200,proportion:0.222}
                    ]
           }
        */
        try {
            //因为有member和order多表是数据，不方便分开，所以直接创建ReportService完成逻辑
            Map<String,Object> resultMap = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //给execl模板填充后台查询到的数据，最后在页面导出execl报表
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){

        try {
            //查询数据库中数据
            Map<String, Object> map = reportService.getBusinessReportData();

            //取出所有数据
            String reportDate = (String) map.get("reportDate");
            Integer todayNewMember = (Integer) map.get("todayNewMember");
            Integer totalMember = (Integer) map.get("totalMember");
            Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");
            Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber");
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");


            /*
            request.getSession().getServletContext()和 request.getServletContext()的区别
            在Windows下的路径分隔符和Linux下的路径分隔符是不一样的，当直接使用绝对路径时，跨平台会暴出“No such file or diretory”的异常。
            所以使用File.separator
             */
            //获取模板文件的绝对路径
            ServletContext servletContext = request.getSession().getServletContext();//全局域对象
            String templateRealPath = servletContext.getRealPath("template") + File.separator + "report_template.xlsx";

            //读取模板文件创建excel对象
            XSSFWorkbook workbook = new XSSFWorkbook(new FileInputStream(new File(templateRealPath)));
            XSSFSheet sheet = workbook.getSheetAt(0);

            //填充数据到表中
            XSSFRow row = sheet.getRow(2);//第三行
            row.getCell(5).setCellValue(reportDate);//第6单元格填充日期

            row = sheet.getRow(4);//第5行
            row.getCell(5).setCellValue(todayNewMember);//填充新增会员数
            row.getCell(7).setCellValue(totalMember);//填充总会员数

            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember);//本周新增会员数
            row.getCell(7).setCellValue(thisMonthNewMember);//本月新增会员数

            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber);//今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);//今日到诊数

            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber);//本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber);//本周到诊数

            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber);//本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);//本月到诊数

            int rowNum = 12;
            for(Map m : hotSetmeal){//热门套餐
                String name = (String) m.get("name");
                Long setmeal_count = (Long) m.get("setmeal_count");//数字没有标注类型，mybatis会自动设置为long类型
                //BigDecimal不可变的、任意精度的有符号十进制数。
                // BigDecimal 由任意精度的整数非标度值 和 32 位的整数标度 (scale) 组成。
                // 如果为零或正数，则标度是小数点后的位数。如果为负数，则将该数的非标度值乘以 10 的负 scale 次幂。
                // 因此，BigDecimal 表示的数值是 (unscaledValue × 10-scale)。
                BigDecimal proportion = (BigDecimal) m.get("proportion");
                row = sheet.getRow(rowNum ++);
                row.getCell(4).setCellValue(name);//套餐名称
                row.getCell(5).setCellValue(setmeal_count);//预约数量
                //将此 BigDecimal 转换为 double
                row.getCell(6).setCellValue(proportion.doubleValue());//占比
            }

            //使用输出流进行表格下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.xlsx");//指定以附件形式进行下载
            workbook.write(out);

            out.flush();
            out.close();
            workbook.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //给PDF模板填充后台查询到的数据，最后在页面导出PDF文件
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response){

        try {
            //查询数据库中数据
            Map<String, Object> map = reportService.getBusinessReportData();

            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");


            /*
            request.getSession().getServletContext()和 request.getServletContext()的区别
            在Windows下的路径分隔符和Linux下的路径分隔符是不一样的，当直接使用绝对路径时，跨平台会暴出“No such file or diretory”的异常。
            所以使用File.separator
             */
            //获取模板文件的绝对路径
            ServletContext servletContext = request.getSession().getServletContext();//全局域对象
            String jrxmlPath = servletContext.getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = servletContext.getRealPath("template") + File.separator + "health_business3.jasper";

            //编译模板文件
            JasperCompileManager.compileReportToFile(jrxmlPath,jasperPath);

            //填充数据-使用javaBean的方式
            JasperPrint jasperPrint = JasperFillManager.fillReport(jasperPath, map, new JRBeanCollectionDataSource(hotSetmeal));

            //使用输出流进行pdf下载,基于浏览器作为客户端下载
            OutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");//代表的是Excel文件类型
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");//指定以附件形式进行下载

            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);

            out.flush();
            out.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
